package com.ww7h.ui.base.ui.adapter

import android.content.Context
import android.util.SparseArray
import android.view.ViewGroup
import androidx.core.util.putAll
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.ww7h.ui.base.ui.adapter.item.ItemRecyclerView
import com.ww7h.ui.base.ui.adapter.item.ItemSpace
import com.ww7h.ui.base.ui.adapter.model.RecyclerViewModel

/**
 * ================================================
 * 描述：
 * 来源：     Android Studio.
 * 项目名：   BigObj
 * 包名：     com.ww7h.ui.base.ui
 * 创建时间：  2020/11/6 01:16
 * @author   ww
 * ================================================
 */
abstract class RecyclerViewAdapter<M: RecyclerViewModel>(private var context: Context) :
    RecyclerView.Adapter<RecyclerViewHolder<M, out ViewDataBinding, out ItemRecyclerView<M, out ViewDataBinding>>>() {

    private val dataList: MutableList<M> by lazy {
        ArrayList()
    }

    fun addAllDataList(dataList: List<M>) {
        this.dataList.addAll(dataList)
        notifyDataSetChanged()
    }

    fun addAllSpaceArray(sparseArray: SparseArray<ItemSpace>) {
        viewHolderFactory.spaceArray.putAll(sparseArray)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerViewHolder<M, out ViewDataBinding, out ItemRecyclerView<M, out ViewDataBinding>> {
        return viewHolderFactory.createViewHolder(context, parent, viewType)
    }

    protected abstract val viewHolderFactory: ViewHolderFactory<M>

    fun getItem(position: Int): M {
        return dataList[position]
    }

    override fun onBindViewHolder(
        holder: RecyclerViewHolder<M, out ViewDataBinding, out ItemRecyclerView<M, out ViewDataBinding>>,
        position: Int
    ) {
        holder.itemRecyclerView.dataBinding(dataList[position], position)
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        recyclerView.addItemDecoration(RecyclerItemDecoration(viewHolderFactory.spaceArray))

    }

}